package s14.ch17.homework;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MyServer {

	public static void main(String[] args) throws IOException, ParseException {
		ServerSocket ss = null;
		int portNumber = 1234;
		ss = new ServerSocket(portNumber);
		while (true) {
			Socket socket = ss.accept();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
					socket.getOutputStream()));
			String message = reader.readLine();
			System.out.println("from client: " + message);
			List<String> elements = stringToList(message);
			List<String> numbers = argsTo(elements);
			List<Integer> numbers2 = new ArrayList<Integer>();
			for (Integer i = 0; i < numbers.size(); i++)
				numbers2.add(Integer.parseInt(numbers.get(i)));
			Integer message2 = numbers2.get(0) + numbers2.get(1);
			writer.write(message2.toString());
			writer.flush();
			if (message.contains("done")) {
				ss.close();
				writer.close();
				break;
			}
		}

	}

	public static List<String> stringToList(String string) {
		List<String> elements;
		elements = Arrays.asList(string.split(" "));
		return elements;
	}

	public static List<String> argsTo(List<String> args) throws ParseException {
		List<String> numbers = new ArrayList<String>();
		for (Integer i = 0; i < (args.size() - 1); i++) {
			numbers.add(new String(args.get(i)));
		}
		return numbers;
	}
}
